import fs from "node:fs/promises";
import path from "node:path";
import { RunnerSpec, TaskHandler } from "../types";
import { resolvePath, ensureDir } from "../utils";
import { writeJsonFile } from "../../../tools/data-processor";

export const previewValidateTask: TaskHandler = async (spec) => {
  const previewFile = spec.schema?.preview;
  if (!previewFile) {
    throw new Error("schema.preview is required for preview.validate");
  }

  const absolutePreview = resolvePath(previewFile);
  const content = await fs.readFile(absolutePreview, "utf-8");
  const componentCount = (content.match(/registerPreview|usePreviewProps/g) || []).length;
  const hasMemo = content.includes("useMemo");
  const hasProps = /props\s*:\s*{/.test(content);

  const report = {
    file: previewFile,
    componentCount,
    hasMemo,
    hasProps,
  };

  const reportRelative = spec.report?.path
    ? spec.report.path.replace(/\.json$/, "-preview.json")
    : path.join("analysis", `${spec.component}-preview-report.json`);
  const outputPath = resolvePath(reportRelative);
  await ensureDir(path.dirname(outputPath));
  await writeJsonFile(outputPath, report);

  return {
    summary: `Preview validate: components=${componentCount}, memo=${hasMemo}`,
    outputPaths: { previewReport: reportRelative },
    data: report,
  };
};
